<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: The this Pointer</title>
  <meta
 content="C++ Tutorial: The this Pointer"
 name="description" />
  <meta
 content="C++ Tutorial, The this Pointer"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">

<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>
<br />
<br />
<br />
<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial - The this Pointer</span></div>
<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>   
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>

<br /><br />
<img src="images/this/DuckYouSanJuMok.png" alt="DuckYouSanJuMok"/>
<br /><br />

<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="thispointer">The this Pointer</div>
<p>When I started leaning C++, one of the big questions was, - What the heck is this <strong>this</strong>? <br />
As it turned out  <strong>this</strong> is a special kind of pointer.  </p>
<p>The <strong>this</strong> pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class. There is a secret not obvious to the new programmers -  <strong>this</strong> pointer holds the key to the question: <br />
<strong> How does C++ know which object it was called on?</strong><br />
The answer is that C++ has a hidden pointer named <strong>this</strong>!</p>
<p>
Suppose that we create an object named <strong>objA</strong> of class A, and class A has a nonstatic member function void f(). If you call the function <strong>objA.f()</strong>, the keyword this in the body of f() stores the address of objA. The type of the this pointer for a member function of a class type A, is <strong>A* const</strong>.</p> 
<p>So, when we call f(), we are actually calling <strong>f(&objA)</strong>. Since C++ converts the function call, it also needs to convert the function itself:</p>
<pre>
void A::f() { }
</pre>
<p>converted internally to: </p>
<pre>
void A:f(A* const this);
</pre>
<p>C++ has added a new parameter to the function. The added parameter is a pointer to the class object the class function is working with. It is always named <strong>this</strong>. The <strong>this</strong> pointer is a hidden pointer inside every class member function that points to the class object. As a result, an object's this pointer is not part of the object itself; it is not reflected in the result of a sizeof statement on the object. Instead, when a nonstatic member function is called for an object, the address of the object is passed by the compiler as a hidden argument to the function. </p>
<p>Let's take a look at a specific example. It's simple calculator code for something like Amazon.com's Cart and CheckOut.</p>
<pre>
#include &lt;iostream&gt;

class Cart {  
private:  
	int total;    
public:  
	Cart(int item){
		this->total = item;
	}  
	Cart& addItem(int itemPrice) { 
		total += itemPrice;
		return *this;
	}
	void checkOut() {
		std::cout << "total: " << total << " $\n";
	}
}; 

int main()
{
	Cart myCart(0);
	myCart.addItem(100);
	myCart.checkOut();
}
</pre>
<p>In the code, when we call</p>
<pre>
myCart.addItem(100);
</pre>
<p>we are actually calling a function converted by compiler:</p>
<pre>
myCart.addItem(&myCart, 100);
</pre>
<p>The function itself should be converted from<br />
<pre>
Cart& addItem(int itemPrice) { 
	total += itemPrice;
	return *this;
}
</pre>
to 
<pre>
Cart& addItem(<font color="blue">myCart* const this,</font> int itemPrice) { 
	<font color="blue">this-></font>total += itemPrice;
	return *this;
}
</pre>
<p>Note that the following expressions are equivalent:</p>
<pre>
this->total;
(*this).total;
</pre>
<p>The fact that the <strong>return type</strong> is a <strong>reference</strong> means that the returned object is the invoking object itself (myCart) rather than a <strong>copy</strong> passed by the <strong>return mechanism</strong>.</p>
<p>In the <strong>main()</strong>, we did not utilize the returned object. If we modify the main a little (chain of <strong>addItem</strong>), we can add as many items we want. Here is a new code.</p>
<pre>
#include &lt;iostream&gt;

class Cart {  
private:  
	int total;    
public:  
	Cart(int item){
		this->total = item;
	}  
	Cart& addItem(int itemPrice) { 
		total += itemPrice;
		return *this;
	}
	void checkOut() {
		std::cout << "total: " << total << " $\n";
	}
}; 

int main()
{
	Cart myCart(0);
	<font color="blue">myCart.addItem(100).addItem(200).addItem(300);</font>
	myCart.checkOut();
}
</pre>
<p>Output is simple:</p>
<pre>
total: 600 $
</pre>
<br />
<br />

<div class="subtitle_2nd" id="constness">Constness of this Pointer</div>
<p>It's worth noting that <strong>this</strong> is a const pointer: we can change the value of the object it points to, but we cannot make it point to something else!  So, we cannot declare the this pointer or make assignments to it.</p>
<p>If the member function is declared with the const qualifier, the type of the this pointer for that member function for class A, is <strong>const A* const</strong>.</p>
<p>
A const this pointer can be used only with const member functions. Data members of the class will be constant within that function. The function is still able to change the value, but requires a const_cast to do so: </p>
<pre>
void A::f() const{    
member = 2010:			// illegal    
const_cast <int&> (member) =2010;	// a bad practice but legal 
}
</pre>
<p>
A better technique would be to declare member <strong>mutable</strong>.
If the member function is declared with the <strong>volatile</strong> qualifier, the type of the this pointer for that member function for class A is volatile A* const. For example, the compiler will not allow the following:</p>
<pre>
class A {
  int n;
  int f() const { return n++; }
};
</pre>
<p>The compiler will not allow the statement n++ in the body of function f(). In the function f(), the this pointer is of type A* const. The function f() is trying to modify part of the object to which this points.</p>
<p>
The this pointer is also used to guard against self-reference:
<pre>
if (&Object != this) {
// do not execute in cases of self-reference 
</pre>
</p>
<br />
<br />

<div class="subtitle_2nd" id="argmatching">Argument Matching </div>
<p>Depending on whether they are declared as <strong>static</strong>, class member functions are treated differently. Since nonstatic functions have an implicit argument that supplies the <strong>this</strong> pointer, nonstatic functions are considered to have one more argument than static functions; otherwise, they are declared identically.</p>
<p>
These nonstatic member functions require that the implied this pointer match the object type through which the function is being called, or, for overloaded operators, they require that the first argument match the object on which the operator is being applied. </p>
<p>
Unlike other arguments in overloaded functions, <strong>no temporary objects</strong> are introduced and <strong>no conversions</strong> are attempted when trying to match the this pointer argument.</p>
<p>
When the -> member-selection operator is used to access a member function, the this pointer argument has a type of class-name * const. If the members are declared as const or volatile, the types are const class-name* const and volatile class-name * const, respectively.</p>
<p>
The . member-selection operator works exactly the same way, except that an implicit & (address-of) operator is prefixed to the object name. <br />
<p>If we write the following code: </p>
<pre>
obj.name
</pre>
<p>The compiler internally treats it like this:</p>
<pre>
(&obj)->name
</pre>
<br />
<br />

<div class="subtitle_2nd" id="constructor">Using this in the constructor</div>
<p>Are we able to use <strong>this</strong> inside the <strong>constructor</strong>? <br />
<p>Quick answer is yes. We are asking this question because we think at the time of using <strong>this</strong> pointer in a constructor, the object is not fully formed yet. However, we can use this in the constructor (in the {body} and even in the initialization list) if we are careful enough. </p>
Here is something that always works: the {body} of a constructor (or a function called from the constructor) can reliably access the data members declared in a base class and/or the data members declared in the constructor's own class. This is because all those data members are guaranteed to have been fully constructed by the time the constructor's {body} starts executing. </p>
<p>But things get complicated when we have to deal with virtual method.........</p>
<br />
<br />

<div class="subtitle_2nd" id="delete">Deleting this Pointer</div>
<p>Deleting this? <br />
No creative mind would do it. Only the destructive mind would try.</p>
<p>Anyway, I think it won't work. Even in the destructor. It may be like deleting null pointer. I tried with my Visual Studio, I couldn't get it done without a crash.</p>
<p>The fundamental issue is how we can figure it out <strong>this</strong> is on the <strong>heap</strong> memory since we can use <strong>delete</strong> only on an object which is on the <strong>heap (free store)</strong> area.</p>
<p>In his book, "More Effective C++ 35 New Ways ...", Scott Meyers concludes, "After all, if we could tell when an address <strong> is</strong> on the heap, we could surely tell when an address is <strong> not</strong> on the heap. But we can't, so we can't. Oh Well. <p>



<br /><br />
<img src="images/this/DuckYouSanJuMok2.png" alt="DuckYouSanJuMok2"/>
<br /><br />

<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
      <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>

</ul>
<br /><br />



<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
